<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { useChatStore } from '@/stores/chat'
import ChatWindow from '@/components/ChatWindow.vue'
import MessageInput from '@/components/MessageInput.vue'
import { ChatWebSocket } from '@/utils/websocket'
import { useAuthStore } from '@/stores/auth'

const chatStore = useChatStore()
const authStore = useAuthStore()
chatStore.setUser(authStore.user?.nickname)
const socket = ref<ChatWebSocket | null>(null)

onMounted(() => {
  socket.value = new ChatWebSocket('ws://localhost:7000/ws')

  socket.value.on('open', () => {
    chatStore.setConnected(true)
    chatStore.addMessage({
      sender: '系统',
      content: '已连接到聊天服务器',
    })

    // 连接成功后，立即发送一条 "加入群聊" 消息
    const message = {
      sender: '系统',
      message: `${chatStore.currentUser} 加入群聊`,
      timestamp: Date.now(),
    }
    socket.value?.send(message)
  })

  socket.value.on('message', (data: { sender: string; message: string; timestamp?: number }) => {
    console.info(data)
    chatStore.addMessage({
      sender: data.sender,
      content: data.message,
    })
  })

  socket.value.on('close', () => {
    chatStore.setConnected(false)
    chatStore.addMessage({
      sender: '系统',
      content: '连接已断开',
    })
  })

  socket.value.on('error', (error: Event) => {
    chatStore.setError(new Error('WebSocket错误'))
    console.error('WebSocket error:', error)
  })

  socket.value.connect()
})

onUnmounted(() => {
  socket.value?.close()
})

const sendMessage = (content: string): void => {
  if (content.trim() && socket.value) {
    const message = {
      sender: chatStore.currentUser,
      message: content,
      timestamp: Date.now(),
    }
    if (socket.value.send(message)) {
      chatStore.addMessage({
        sender: chatStore.currentUser,
        content,
      })
    }
  }
}
</script>

<template>
  <div class="chat-container">
    <ChatWindow />
    <MessageInput @send="sendMessage" />
  </div>
</template>

<style scoped>
/* 样式保持不变 */
</style>
